package me.passtime.projt.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Map.Entry;

import me.passtime.projt.Const;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;


/**
 * HTTP连接工具。应 与GUI运行在不同线程下。
 */
class HttpConnection {

	private boolean mAbort;// 是否主动关闭连接
	private HttpClient mClient;
	private HttpPost mPost;

	public void abort() {
		mAbort = true;
		Log.e(Const.TAG, "HttpConnection:abort request");
		if (mPost != null) {
			mPost.abort();
		}
		closeConnection();
	}

	/**
	 * 主动关闭网络连接。
	 */
	public void closeConnection() {
		if (mClient != null) {
			Log.i(Const.TAG, "HttpConnection:close connection");
			mClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 发起POST请求，取得响应字符串。如果HTTP StatusCode不是200，则返回null。
	 * 
	 * @param uri
	 * @return
	 * @throws NetworkingException
	 * @throws NetworkingAbortException
	 */
	String post(UriConstants uri, String data)
			throws NetworkingException, NetworkingAbortException {
		Log.d(Const.TAG, "HttpConnection:HTTP POST excuting");
		mAbort = false;
		mClient = new DefaultHttpClient();
		BufferedReader br = null;
		String resp = null;
		try {
			mPost = new HttpPost(uri.getUri());
//			List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//			if (params != null) {
//				for (Entry<String, String> item : params.entrySet()) {
//					postParameters.add(new BasicNameValuePair(item.getKey(),
//							item.getValue()));
//				}
//			}
//			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
//					postParameters);
            StringEntity myEntity = new StringEntity(data, "utf-8");
            mPost.setEntity(myEntity);
			HttpResponse response = mClient.execute(mPost);

			br = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			String line = "";
			String newLine = System.getProperty("line.separator");
			StringBuffer sb = new StringBuffer("");
			while ((line = br.readLine()) != null) {
				sb.append(line + newLine);
			}
			resp = sb.toString();
			Log.v(Const.TAG, "HttpConnection:response string:"
					+ resp);

			int statusCode = response.getStatusLine().getStatusCode();
			Log.d(Const.TAG,
					"HttpConnection:response status code:" + statusCode);

			if (statusCode != HttpStatus.SC_OK) {
				Log.e(Const.TAG,
						"HttpConnection:wrong response status code:"
								+ statusCode);
				Log.d(Const.TAG,
						"HttpConnection:HTTP POST response string:"
								+ sb.toString());
				resp = null;
			}

		} catch (IOException e) {
			Log.e(Const.TAG, "HttpConnection:is aborted?"
					+ mAbort);
			Log.e(Const.TAG,
					"HttpConnection:I/O exception:" + e.getMessage());
			resp = null;
			if (!mAbort) {
				throw new NetworkingAbortException();
			} else {
				throw new NetworkingException(e);
			}
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				if (mClient != null) {
					mClient.getConnectionManager().shutdown();
					Log.i(Const.TAG,
							"HttpConnection:connection closed");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.d(Const.TAG, "HttpConnection:HTTP POST finished");
		return resp;
	}

}
